const app = getApp();
let filter = require('../../../utils/intercept.js')
const http = require('../../../utils/http.js')

Page(filter.identityFilter({

    /**
     * 页面的初始数据
     */
    data: {
        loadModal: false,
        isShow: false,
        outTradeNo: "",
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        coupon: {},
        array: ['上午', '下午'],
        date:'',
        show: false,
        show1: false,
        customer:null,
        // canvas 
        _width: 0, //手机屏宽
        _heigth: 0,//手机屏高
        swiperHeight: 0,//主图图片高度
        canvasType: false,//canvas是否显示
        loadImagePath: '',//下载的图片
        imageUrl: null, //主图网络路径
        codeUrl: null,//二维码网络路径
        localImageUrl: '', //绘制的商品图片本地路径
        localCodeUrl: '', //绘制的二维码图片本地路径
        loadType: false  //保存图片，分享好友 Btn
    },
    // 获取图片信息
getImginfo: function(urlArr, _type) {
  let that = this;
  wx.getImageInfo({
      src: urlArr[_type], //服务器返回的带参数的小程序码地址
      success: function(res) {
          //res.path是网络图片的本地地址
          if (_type === 0) { //商品图片
              that.setData({
                  localImageUrl: res.path,
              })
              console.log(that.data.localImageUrl)
              that.getImginfo(urlArr, 1)
          } else {
              that.setData({ //二维码
                  localCodeUrl: res.path,
                  loadType: true,
              })
              console.log(that.data.localCodeUrl)
              // 创建canvas图片
              that.createNewImg();
          }
      },
      fail: function(res) {
          //失败回调
          console.log('错误-res', _type, res)
      }
  });
},
//绘制canvas
createNewImg: function() {
  let _width = this.data._width,
      _heigth = this.data._heigth; //屏幕宽与高

  let imgHeigth = this.data.swiperHeight, //原图片高度
      scale = (_width - 40) / _width, //缩小比例
      that = this;
  let imgH = imgHeigth * scale; //绘制时图片显示高度  
  let ctx = wx.createCanvasContext('mycanvas');
  // 绘制背景
  ctx.setFillStyle("#fff");
  ctx.fillRect(0, 0, _width - 40, imgH + 160);
  //绘制图片
  // ctx.drawImage(this.data.localImageUrl, 10, 10,200, 500);
  ctx.drawImage(this.data.localImageUrl, 10, 10, _width - 60, imgH - 320);

  // 绘制标题
  ctx.setFontSize(18);
  ctx.setFillStyle('#333');

  let txtWidth = _width - 60 + 30 - 100 - 50; //文字的宽度

  //商品名称 最多两行显示 写法有点LOW，但思路是这样的
  //console.log(this.data.coupon.stockName.length)
  let title = this.data.coupon.name; //商品名称
  let title2; //商品名称
  if (this.data.coupon.name.length > 10) {
      title2 = title.slice(10, title.length);
      title = title.slice(0, 10);
      if (title2.length > 10) {
        title2 = title2.slice(0, 9) + ' ...';
      }
  }
  
  ctx.fillText(title, 10, imgH -280, txtWidth);
  if(title2){
    ctx.fillText(title2, 10, imgH -250 , txtWidth);
  }
  
  // 绘制价格 '￥'
  ctx.setFontSize(14);
  ctx.setFillStyle('#d2aa68');
  ctx.fillText('￥', 10, imgH -200, txtWidth);
  // 绘制价格
  ctx.setFontSize(24);
  ctx.fillText(this.data.coupon.amount, 26, imgH -200, txtWidth);
  // 绘制门市价
  ctx.setFontSize(14);
  ctx.setFillStyle('#666');
  ctx.fillText(`原价￥${this.data.coupon.costPrice}`, 115, imgH -200, txtWidth);

  // 绘制二维码
  ctx.drawImage(this.data.localCodeUrl, _width - 80 + 80 - 150, imgH - 300, 100, 100);
  // 显示绘制
  ctx.draw();

  //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
  setTimeout(function() {
      wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function(res) {
              var tempFilePath = res.tempFilePath;
              that.setData({
                  loadImagePath: tempFilePath,
              });
          },
          fail: function(res) {
              console.log(res);
          }
      });
  }, 1000);
},
    showPopup() {
      //console.log(this.data.coupon.stockId)
      http.get('/api/index/createWxaCodeUnlimit', {path: 'pages/home/couponDetail/index',productId: this.data.coupon.id}).then(res1 => {
        if (res1.code == 200) {
          //console.log(res1)
          this.setData({ 
            show1: true,
            codeUrl:res1.data.replace('http://file.alipayjf.com','https://qianhuyun003.oss-cn-beijing.aliyuncs.com')
           });
          /*获取手机宽高*/
          let that = this
          let imgUrl = this.data.imageUrl
          let qrcodeUrl = this.data.codeUrl
          wx.getSystemInfo({
              success(res) {
                  that.setData({
                      _width: res.windowWidth,
                      _heigth: res.windowHeight,
                      canvasType: true,
                      
                  })
                  // 获取图片信息生成canvas
                  that.getImginfo([imgUrl, qrcodeUrl], 0);
              }
          })
        }
      })
      
    },
  
    onClose1() {
      this.setData({ show1: false });
    },
    //分享获取图片主图尺寸
    onImgLoad: function(e) {
      let oImgW = e.detail.width; //图片原始宽度
      let oImgH = e.detail.height; //图片原始高度
      let imgWidth = 750; //图片设置的宽度
      let scale = imgWidth / oImgW; //比例计算
      let imgHeight = oImgH * scale;
  
      this.setData({
          swiperHeight: imgHeight,
          canvasW: imgWidth-70,
          canvasH: imgHeight-260
      })
    },
    // 购物车界面跳转
    gwcBtn:function(){
      wx.switchTab({
        url: '/pages/user/shoppingCart/shoppingCart'
      })
    },
    //店铺跳转
    productDetailClick:function(e){
      wx.navigateTo({
        url: '/pages/home/store/index?id='+e.currentTarget.dataset.id,
      })
    },
    onClose() {
      this.setData({ show: false });
    },
    formatDate(date) {
      date = new Date(date);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    formatDate1(date) {
        date = new Date(date);
        var yue=date.getMonth() + 1
        var ri=date.getDate()
        if(parseInt(yue) < 10){  
          yue = '0'+yue 
        }
        if(parseInt(ri) < 10){  
          ri = '0'+ri 
        }
        return `${date.getFullYear()}-${yue}-${ri}`;
    },
    onConfirm(event) {
        //console.log(event.detail)
      let that = this;
      this.setData({
        show: false,
        date: this.formatDate1(event.detail)
        //isShow: 'show'//ui组件
      });
      http.get('/api/index/sendCoupon', {stockId: this.data.coupon.stockId,useDate:this.data.date}).then(res => {
        this.setData({loadModal: false})
        if (res.code == 200) {
            //需要购买发起支付
            if (this.data.coupon.amount > 0) {
                let outTradeNo = res.result.outTradeNo
                wx.requestPayment({
                    timeStamp: res.result.timeStamp,
                    nonceStr: res.result.nonceStr,
                    package: res.result.packageValue,
                    signType: res.result.signType,
                    paySign: res.result.paySign,
                    success(res) {
                        if (res.errMsg = "requestPayment:ok") {
                            that.successAfter(outTradeNo)
                        }
                    }
                })
            } else {
                //不需要购买发放成功
                this.successAfter(res.result)
            }
            this.setData({
              date:null
            })
        } else {
            wx.showModal({
                content: res.message,
                showCancel: false,
            })
        }
      })
    },

    radioChange(e) {
      //console.log('radio发生change事件，携带value值为：', this.data.date)
      //console.log(this.data.date)
      this.setData({
        isShow: ''//ui组件
      });
      if (!this.data.date){
        wx.showToast({
          title: '信息未填写完整',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false
      }

      this.setData({loadModal: true})
      
    },
    //时段选择
    // bindPickerChange: function(e) {
    //   //console.log('picker发送选择改变，携带值为', e.detail.value)
    //   this.setData({
    //     index: e.detail.value
    //   })

    // },
    //日期选择
    // bindDateChange: function(e) {
    //   console.log('picker发送选择改变，携带值为', e.detail.value)
    //   this.setData({
    //     date: e.detail.value
    //   })
    // },
    // //身份证号
    // input: function (e) {
    //    //console.log(e);
    //   this.setData({ inputVal: e.detail.value });
    // },
    //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //点击我显示底部弹出框
  // clickme: function () {
  //   this.showModal();
  // },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })

    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      //console.log(decodeURIComponent(options.scene))
      var scene=options.id
      if(options.scene){
        scene = decodeURIComponent(options.scene)
        scene=scene.split('&')
        scene=scene[0]
      }
      wx.hideShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })
      
      if (options.shareUser) {
        this.setData({
          shareUser:options.shareUser,
          stockIdId:options.id
        })
      }
      if(options.time){
        this.setData({
          time:(options.time).replace(/-/g,"/")
        })
      }
      var that=this
      var arr,arr1
      this.setData({
        customer: app.globalData.customer
      })
      http.get('/api/purchase/selectEquityCardDetail', {id: scene}).then(res => {
        if (res.code == 200) {
          //arr=res.result.availableBeginTime.split(' ')
          //arr1=res.result.availableEndTime.split(' ')
            this.setData({
                coupon: res.data,
                //arr: arr[0],
                //arr1: arr1[0],
                //time: new Date().toLocaleDateString(),
                imageUrl:res.data.fileUrl.replace('http://file.alipayjf.com','https://qianhuyun003.oss-cn-beijing.aliyuncs.com'),
            })
            console.log(this.data.coupon)
            //console.log(new Date().toLocaleDateString())
        }
      })
        

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      //console.log('987')
      if(this.data.stockIdId && this.data.shareUser && wx.getStorageSync("token")){
        http.get('/api/purchase/selectEquityCardDetail', {id: this.data.stockIdId,shareUserId:this.data.shareUser}).then(res => {
          if (res.code == 200) {
            //arr=res.result.availableBeginTime.split(' ')
            //arr1=res.result.availableEndTime.split(' ')
              this.setData({
                  coupon: res.data,
                  //arr: arr[0],
                  //arr1: arr1[0],
                  //time: new Date().toLocaleDateString(),
                  imageUrl:res.data.fileUrl.replace('http://file.alipayjf.com','https://qianhuyun003.oss-cn-beijing.aliyuncs.com'),
              })
              console.log(this.data.coupon)
              //console.log(new Date().toLocaleDateString())
          }
        })
      }
    },
    //加入购物车
    cartBtn:function(){
      var cart=new Array()
      if(wx.getStorageSync('cart').length){
        cart=wx.getStorageSync('cart')
      }
      cart.push(this.data.coupon)
      wx.setStorageSync('cart',cart)
      wx.showToast({
        title:'已添加到购物车',
        icon:'none'
      })
    },
    moban:function() {
      var that=this
      var arr1=[]
      //console.log(this.data.customer.templateId)
      if(this.data.customer.templateId){
        //console.log(this.data.customer.templateId)
        arr1=(this.data.customer.templateId).split("|")
        //console.log(arr1)
        wx.requestSubscribeMessage({
          tmplIds: arr1,
          success (res) {
            //console.log(re1)
            that.buyCoupon()
          },
          fail(e){
            console.log(e)
          }
        })
      }else{
        that.buyCoupon()
      }
    },

    buyCoupon() {
      let that = this;
      var shareUser=''
        if(this.data.coupon.type==5){
          this.setData({
            show:true
          })
        }else{
          wx.showModal({
            title: '提示',
            content: '你是否确定兑换或购买该商品？',
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.showLoading({
                  title: '加载中',
                  mask: true
                })
                if(that.data.shareUser){
                  shareUser=that.data.shareUser
                }
                http.get('/api/purchase/buyEquityCard', {id: that.data.coupon.id,shareUser:shareUser}).then(res => {
                  wx.hideLoading()
                  if (res.code == 200) {
                          let outTradeNo = res.data.outTradeNo
                          wx.requestPayment({
                              timeStamp: res.data.timeStamp,
                              nonceStr: res.data.nonceStr,
                              package: res.data.package,
                              signType: res.data.signType,
                              paySign: res.data.paySign,
                              success(res) {
                                  if (res.errMsg = "requestPayment:ok") {
                                      that.successAfter(outTradeNo)
                                  }
                              }
                          })
                  } else {
                      wx.showModal({
                          content: res.message,
                          showCancel: false,
                      })
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          
        }
        
        //this.showModal();

    },
    //
    successAfter(outTradeNo) {
      let that = this;
      // wx.showToast({
      //     title: '购买成功',
      //     icon: 'success'
      // })
      wx.showModal({
        title: '购买成功',
        content: '请去个人中心-我的优惠券中查看领取',
        success (res) {
          if (res.confirm) {
            //console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/user/mycoupon/index',
            })
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      });
      //减去详情页面数量
      let data = Object.assign(this.data.coupon, {distributedCoupons: this.data.coupon.distributedCoupons + 1})
      this.setData({
          loadModal: false,
          coupon: data
      })
  },
    // successAfter(outTradeNo) {
    //     let that = this;
    //     if (that.data.coupon.stockType == 'merNORMAL') { //如果是商家券,过1秒去查询是否支付成功
    //         setTimeout(function () {
    //             that.setData({
    //                 isShow: true,
    //                 outTradeNo: outTradeNo
    //             })
    //         }, 800)
    //     } else { //不是商家券提示购买成功
    //         wx.showToast({
    //             title: '购买成功',
    //             icon: 'success'
    //         })
    //     }
    //     //减去详情页面数量
    //     let data = Object.assign(this.data.coupon, {distributedCoupons: this.data.coupon.distributedCoupons + 1})
    //     this.setData({
    //         loadModal: false,
    //         coupon: data
    //     })
    // },
    //点击保存到相册
    saveImg: function() {
      var that=this
        //这里可以打印出返回的临时文件路径
        
      console.log('123')
      wx.saveImageToPhotosAlbum({
          filePath: that.data.loadImagePath,
          success(res) {
              console.log('res', res);
              wx.showToast({
                  title: '已保存到相册',
                  icon: 'success',
                  duration: 3000
              })
          },
          fail(res) {
              console.log('错误', res);
              console.log(that.data.loadImagePath)
              wx.openSetting({//进入小程序授权设置页面
                success(settingdata) {
                console.log(settingdata)
                if (settingdata.authSetting['scope.writePhotosAlbum']) {//用户打开了保存图片授权开关
                
                } else {//用户未打开保存图片到相册的授权开关
                wx.showModal({
                  title: '温馨提示',
                  content: '授权失败，请稍后重新获取',
                  showCancel: false,
                })
                }
                }
                })
          }
      })
    },

    //分享
    onShareAppMessage(res) {
        //console.log(this.data.coupon.stockId)
        if(res.from==='button'){
          return {
            title: this.data.coupon.name,
            //imageUrl: '/images/share.jpg',
            path: '/pages/home/equityCard/index?id=' + this.data.coupon.id + "&shareUser=" + wx.getStorageSync("userInfo").id
          }
        }
        
    },
    

}))
